import React, { useState } from 'react';
import { Form, Input, Upload, Button, Select, Switch, Avatar, Space, message, Radio } from 'antd';
import { UserOutlined, UploadOutlined } from '@ant-design/icons';
import { userStore } from '../store/userStore';
import { roleStore } from '../../role/store/roleStore';
import { Editor_Default_Directory } from '@/globals/document';
import { uploadFile } from '../../../../../apis/public/upload';
import { getDownloadUrl } from '@/utils/fileUtil';
import { User } from '../store/userTypes';

const { Option } = Select;

interface UserFormProps {
  type: 'create' | 'edit' | 'view';
  initialValues?: any;
  onCancel: () => void;
}

const UserForm: React.FC<UserFormProps> = ({ type, initialValues, onCancel }) => {
  const [form] = Form.useForm();
  const [avatarUrl, setAvatarUrl] = useState<string>(`/api/starhub/document/download/${initialValues?.avatar}` || '');
  const [avatar, setAvatar] = useState<string>(initialValues?.avatar || '');

  const beforeUpload = (file: File) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      message.error('只能上传图片文件！');
      return Upload.LIST_IGNORE;
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过 2MB！');
      return Upload.LIST_IGNORE;
    }
    return true; // 验证通过，允许上传
  };

  const customRequest = async (options: any) => {
    try {
      // 本地预览
      const reader = new FileReader();
      reader.readAsDataURL(options.file);
      reader.onload = () => {
        setAvatarUrl(reader.result as string);
      };
      
      // 拼接文件上传参数
      const formData = new FormData();
      formData.append('file', options.file);
      formData.append('fileName', options.file instanceof File ? options.file.name : 'unknown');
      formData.append('uid', options.file?.uid);
      formData.append('directoryId', Editor_Default_Directory.toString());
      const response = await uploadFile(formData);

      if (options.onSuccess) {
        if(window.HubUser?.avatar){
          let avatarUrl = await getDownloadUrl(window.HubUser?.avatar);
          setAvatar(response.data.page?.[0].id);
          setAvatarUrl(avatarUrl);
        }  
        options.onSuccess(response);
      }
      //文件内容提取
      //onUploadSuccess(file); // 调用上传成功回调函数
    } catch (error) {
      if (options.onError) {
        options.onError(error instanceof Error ? error : new Error('上传失败'));
      }
    }
  };


  const onFinish = (values: User) => {
    values.avatar = avatar;
    userStore.saveUser(values);
    onCancel();
  };

  const isViewMode = type === 'view';

  return (
    <Form
      form={form}
      layout="vertical"
      onFinish={onFinish}
      initialValues={{
        ...initialValues,
        status: initialValues?.status === 'active',
      }}
      disabled={isViewMode}
    >
      <Form.Item label="头像" name="avatar"  >
        <Space direction="vertical" align="center">
          <Avatar 
            size={100} 
            src={avatarUrl} 
            icon={<UserOutlined />}
          />
          {!isViewMode && (
             <Upload
                beforeUpload={beforeUpload}
                maxCount={1}
                customRequest={(options) => {customRequest(options)}}
                showUploadList={false}
                onRemove={()=> { }}
                accept=".png, .jpeg, .jpg, .gif, .bmp, .tiff, .svg, .webp, .ico, .psd, .raw, .heic, .heif"
              >
                <Button icon={<UploadOutlined />}>上传头像</Button>
              </Upload>
          )}
        </Space>
      </Form.Item>

      <Form.Item
        label="用户名"
        name="username"
        rules={[{ required: true, message: '请输入用户名！' }]}
      >
        <Input placeholder="请输入用户名" />
      </Form.Item>

      <Form.Item
        label="真实姓名"
        name="name"
        rules={[{ required: true, message: '请输入真实姓名！' }]}
      >
        <Input placeholder="请输入真实姓名" />
      </Form.Item>

      <Form.Item
        label="性别"
        name="gender"
        rules={[{ required: false, message: '请选择性别！' }]}
      >
        <Radio.Group defaultValue="male">
          <Radio value="male">男</Radio>
          <Radio value="female">女</Radio>
          <Radio value="secret">保密</Radio>
        </Radio.Group>
      </Form.Item>

      <Form.Item
        label="邮箱"
        name="email"
        rules={[
          { required: false, message: '请输入邮箱！' },
          { type: 'email', message: '请输入有效的邮箱地址！' }
        ]}
      >
        <Input placeholder="请输入邮箱" />
      </Form.Item>

      <Form.Item
        label="手机号"
        name="phone"
        rules={[
          { required: false, message: '请输入手机号！' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号！' }
        ]}
      >
        <Input placeholder="请输入手机号" />
      </Form.Item>

      {/* <Form.Item
        label="部门"
        name="department"
        rules={[{ required: false, message: '请选择部门！' }]}
      >
        <Select placeholder="请选择部门">
          <Option value="技术部">技术部</Option>
          <Option value="市场部">市场部</Option>
          <Option value="人事部">人事部</Option>
          <Option value="财务部">财务部</Option>
        </Select>
      </Form.Item> */}

      {/* <Form.Item
        label="职位"
        name="position"
        rules={[{ required: false, message: '请输入职位！' }]}
      >
        <Input placeholder="请输入职位" />
      </Form.Item> */}

      <Form.Item
        label="角色"
        name="roleId"
        rules={[{ required: false, message: '请选择角色！' }]}
      >
          <Select  placeholder="请选择角色" defaultValue="3">
            {userStore.roleValues && Object.entries(userStore.roleValues).map(([roleId, roleConfig]) => (
                <Option key={roleId} value={roleId}>
                  {(roleConfig as any).title}
                </Option>
              ))}
          </Select>
      </Form.Item>
      <Form.Item
        label="状态"
        name="status"
        valuePropName="checked"
      >
        <Switch checkedChildren="启用" unCheckedChildren="禁用" />
      </Form.Item>

      {!isViewMode && (
        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit">
              {type === 'create' ? '创建' : '保存'}
            </Button>
            <Button onClick={onCancel}>取消</Button>
          </Space>
        </Form.Item>
      )}
    </Form>
  );
};

export default UserForm; 